package com.watson.nettydemo.demo04;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @date: 2022/3/11 15:19
 * @version: 1.0
 */
public class SocketClientHandler  extends ChannelInboundHandlerAdapter {

    /**
     * 当channel被激活以后会触发该方法的执行。互发消息的第一条
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        // 申请缓存空间
        for (int i = 0; i < 200; i++) {
            String s = i+"";
            byte[] bytes = s.getBytes();
            ByteBuf buffer = Unpooled.buffer(s.length());
            buffer.writeBytes(bytes);
            // 将缓存数据写到channel
            ctx.writeAndFlush(buffer);
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
